package com.baozheyangken.ai_learn.controller;

import com.baozheyangken.ai_learn.annotation.RequiresAuthentication;
import com.baozheyangken.ai_learn.pojo.entity.Question;
import com.baozheyangken.ai_learn.pojo.entity.QuestionType;
import com.baozheyangken.ai_learn.pojo.result.Result;
import com.baozheyangken.ai_learn.service.QuestionService;
import com.baozheyangken.ai_learn.mapper.UserMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/api/questions")
@RequiresAuthentication
public class QuestionController {
    private static final Logger log = LoggerFactory.getLogger(QuestionController.class);

    @Autowired
    private QuestionService questionService;

    @Autowired
    private UserMapper userMapper;
    
    //获取所有类型
    @GetMapping("/type")
    public Result<List<QuestionType>> getType(){
        return Result.success(questionService.getQuestionType());
    }

    // 新建题目（含知识点关联）
    @PostMapping
    public Result<String> addQuestion(@RequestBody Map<String, Object> params) {
        try {
            Question question = new Question();
            // 转换请求参数到Question对象
            question.setContent((String) params.get("content"));
            Integer typeId = Integer.parseInt(params.get("typeId").toString());
            question.setTypeId(typeId);
            int difficultyId = Integer.parseInt(params.get("difficultyId").toString());
            log.info("插入题目时的difficulty_id: {}", difficultyId);
            question.setDifficultyId(difficultyId);
            Integer userId = Integer.parseInt(params.get("userId").toString());
            // 额外验证用户 ID 是否存在
            if (!userMapper.existsById(userId)) {
                return Result.error("您输入的用户 ID 不存在，请检查后重新输入");
            }
            question.setUserId(userId);
            question.setExplanation((String) params.get("explanation"));

            @SuppressWarnings("unchecked")
            List<Integer> knowledgeIds = (List<Integer>) params.get("knowledgeIds");
            int id = questionService.addQuestion(question, knowledgeIds);
            return Result.success(id + "添加成功");
        } catch (Exception e) {
            return Result.error("添加失败：" + e.getMessage());
        }
    }

    // 删除题目
    @DeleteMapping("/{id}")
    public Result<String> deleteQuestion(@PathVariable Integer id) {
        int result = questionService.deleteQuestionById(id);
        return result > 0 ? Result.success("删除成功") : Result.error("删除失败");
    }

    // 更新题目
    @PutMapping
    public Result<String> updateQuestion(@RequestBody Map<String, Object> params) {
        try {
            Question question = new Question();

            // 处理 id 参数
            Object idObj = params.get("id");
            if (idObj != null) {
                question.setId(Integer.parseInt(idObj.toString()));
            } else {
                return Result.error("题目 ID 不能为空");
            }

            // 处理 content 参数
            Object contentObj = params.get("content");
            if (contentObj != null) {
                question.setContent(contentObj.toString());
            }

            // 处理 typeId 参数
            Object typeIdObj = params.get("typeId");
            if (typeIdObj != null) {
                question.setTypeId(Integer.parseInt(typeIdObj.toString()));
            }

            // 处理 difficultyId 参数
            Object difficultyIdObj = params.get("difficultyId");
            if (difficultyIdObj != null) {
                question.setDifficultyId(Integer.parseInt(difficultyIdObj.toString()));
            }

            // 处理 explanation 参数
            Object explanationObj = params.get("explanation");
            if (explanationObj != null) {
                question.setExplanation(explanationObj.toString());
            }

            @SuppressWarnings("unchecked")
            List<Integer> knowledgeIds = (List<Integer>) params.get("knowledgeIds");

            int result = questionService.updateQuestion(question, knowledgeIds);
            return result > 0 ? Result.success("更新成功") : Result.error("更新失败");
        } catch (Exception e) {
            return Result.error("更新失败：" + e.getMessage());
        }
    }

    // 查询题目列表（支持条件过滤）
    //todo 应该为分页查询
    @GetMapping("/questions")
    public Result<List<Question>> getQuestions(@RequestParam Map<String, Object> params) {
        // 处理可能为 null 的参数
        if (params.containsKey("keyword")) {
            Object keywordObj = params.get("keyword");
            if (keywordObj == null) {
                params.put("keyword", null);
            } else {
                params.put("keyword", keywordObj.toString());
            }
        }

        // 处理其他可能为 null 的参数，例如 typeId 和 difficultyId
        if (params.containsKey("typeId")) {
            Object typeIdObj = params.get("typeId");
            if (typeIdObj == null) {
                params.put("typeId", null);
            } else {
                try {
                    params.put("typeId", Integer.parseInt(typeIdObj.toString()));
                } catch (NumberFormatException e) {
                    params.put("typeId", null);
                }
            }
        }

        if (params.containsKey("difficultyId")) {
            Object difficultyIdObj = params.get("difficultyId");
            if (difficultyIdObj == null) {
                params.put("difficultyId", null);
            } else {
                try {
                    params.put("difficultyId", Integer.parseInt(difficultyIdObj.toString()));
                } catch (NumberFormatException e) {
                    params.put("difficultyId", null);
                }
            }
        }

        List<Question> questions = questionService.getAllQuestions(params);
        return Result.success(questions);
    }
}